﻿
CREATE PROCEDURE [dbo].[SupplierInvoiceLinesDelete]
(
	@Original_Id int,      --CD.InputLines.Id
	@Original_MD datetime	 --CD.InputLines.MD
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @orgPartyId int

	SET NOCOUNT ON

IF (@Original_Id Is Null) OR (@Original_MD Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @orgPartyId = P.Id
FROM CD.InputLines I LEFT OUTER JOIN CD.Parties P ON I.Id = P.InputLineId AND I.DocId = P.DocId
WHERE I.Id = @Original_Id AND I.MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

EXEC @intRet = dbo.CheckAllowUpdateDeleteForRecord @Original_Id
IF @intRet <> 0 RETURN @intRet

BEGIN TRAN

IF @orgPartyId Is NOT Null
BEGIN

	EXEC @intRet = dbo.PartyGoodsDelete @orgPartyId, 1
	IF @intRet <> 0 
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		RETURN @intRet
	END

END

	SET NOCOUNT OFF;
DELETE FROM CD.InputLines WHERE Id = @Original_Id

SELECT @intRet = @@rowcount, @intErrCode = @@error
IF (@intErrCode <> 0)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	RETURN @intErrCode
END
IF (@intRet <> 1)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 6, 
	@strMsg = 'Строка приходной накладной не удалена!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

COMMIT TRAN

RETURN 0
